﻿package cc.telecomdigital.tdstock.trading;

import java.util.ArrayList;
import java.util.List;

import com.lightstreamer.ls_client.UpdateInfo;

import cc.telecomdigital.tdstock.R;
import cc.telecomdigital.tdstock.Framework.Application_Framework.LS_ItemRequestType;
import cc.telecomdigital.tdstock.Framework.UniqueItem.DeviceInfo;
import cc.telecomdigital.tdstock.Framework.UniqueItem.TDStockLog;
import cc.telecomdigital.tdstock.Services.LS_SubscriptionItem;
import cc.telecomdigital.tdstock.Services.LS_UserClient.CONNECTION_STATUS;
import cc.telecomdigital.tdstock.Services.LS_UserClient.ILS_UserClient_Authentication_Report;
import cc.telecomdigital.tdstock.Services.LS_UserClient.ILS_UserClient_Response;
import cc.telecomdigital.tdstock.Services.LS_UserClient.LS_UserClient_Authentication_Result;

import cc.telecomdigital.tdstock.trading.Common.Trade_AppConstant;
import cc.telecomdigital.tdstock.trading.Common.Trade_StockHistItem;
import cc.telecomdigital.tdstock.trading.Common.Trade_SymbolTranslation;
import cc.telecomdigital.tdstock.trading.Services.TradeAppInfo;
import cc.telecomdigital.tdstock.trading.Services.TradeGetMultipleOrder;
import cc.telecomdigital.tdstock.trading.Services.TradeGetMultipleOrder.ITradeGetMultipleOrderResponse;
import cc.telecomdigital.tdstock.trading.Services.TradeGetMultipleOrder.TradeGetMultipleOrderResult;
import cc.telecomdigital.tdstock.trading.Tools.Trade_StockFunctionTools;
import cc.telecomdigital.tdstock.trading.widget.AppDialogOK;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Bundle;
import android.os.Handler;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.WindowManager.LayoutParams;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class Trade_AcctOrder_SubActivity extends Trade_TemplateActivity
	implements View.OnClickListener, OnItemClickListener,
	RadioGroup.OnCheckedChangeListener, ILS_UserClient_Response
{
	public enum STOCK_ORDER_FILTER_TYPE
	{
		PROCESSING, FINISH, ALL
	}

	private STOCK_ORDER_FILTER_TYPE	filterType	= STOCK_ORDER_FILTER_TYPE.ALL;

	// Happen within the scope
	private List<Trade_StockHistItem>	transStorageList;
	private int					prevWidth;
	private String                     systemLang;
	
	@Override
	public void onCreate(Bundle iSaveInstance)
	{
		super.onCreate(iSaveInstance);
		setContentView(R.layout.account_stockorder);
		systemLang = DeviceInfo.GetLanguageString();
		
		TextView textViewObj = (TextView) findViewById(R.id.view_acctheader_Title);
		if (TradeAppInfo.IsDemoAccount())
			textViewObj.setText(TradeAppInfo.GetUserName());
		else
			textViewObj.setText(R.string.transHistoryText);

		ImageButton imgButton;

		imgButton = (ImageButton) findViewById(R.id.view_acctheader_Refresh);
		imgButton.setVisibility(View.VISIBLE);
		imgButton.setOnClickListener(this);

		imgButton = (ImageButton) findViewById(R.id.view_acctheader_Home);
		imgButton.setOnClickListener(this);

		// Display the filter item
		stockDisplayList = new ArrayList<Trade_StockHistItem>();

		stockDisplayListAdapter = new TransactionItemAdapter(this,
				android.R.layout.simple_list_item_1,
				R.layout.view_stockorder_itemlist, fScrWidthPixel,
				stockDisplayList);

		stockDisplayListView = (ListView) findViewById(R.id.account_stockorder_List);
		stockDisplayListView.setDividerHeight(0);
		stockDisplayListView.setOnItemClickListener(this);
		stockDisplayListView.setAdapter(stockDisplayListAdapter);

		RadioGroup rGroup;
		RadioButton rButton;

		if (filterType == STOCK_ORDER_FILTER_TYPE.PROCESSING)
			rButton = (RadioButton) findViewById(R.id.account_stockorder_OptInProgressRadio);
		else if (filterType == STOCK_ORDER_FILTER_TYPE.FINISH)
			rButton = (RadioButton) findViewById(R.id.account_stockorder_OptDoneRadio);
		else
			rButton = (RadioButton) findViewById(R.id.account_stockorder_OptAllRadio);

		if (rButton != null)
			rButton.setChecked(true);

		rGroup = (RadioGroup) findViewById(R.id.account_stockorder_OptRadioGroup);
		rGroup.setOnCheckedChangeListener(this);

		prevWidth = 0;

	}
	
	@Override
	public void onResume()
	{
		super.onResume();
		systemLang = DeviceInfo.GetLanguageString();
		LayoutAdjustment(fScrWidthPixel);

		if (TradeAppInfo.IsStockHistoryEmpty() == false)
		{
			transStorageList = TradeAppInfo.GetStockHistoryItemList();
			InformationRefresh(filterType, true);
			SubscribeAccountOrder();
		}
		else
			StockOrderDataRequest();
	}	
	
	@Override
	public void onBackPressed()
	{
		SwitchFreeActivity(Trade_tradingOptionActivity.class);		
	}
	
	private void LayoutAdjustment(int iScrWidth)
	{
		if (prevWidth != iScrWidth)
		{
			prevWidth = iScrWidth;
			stockDisplayListAdapter.SetScreenWidth(iScrWidth);
			stockDisplayListAdapter.notifyDataSetInvalidated();
		}
	}

	@Override
	public void onConfigurationChanged(Configuration iChange)
	{
		super.onConfigurationChanged(iChange);
		LayoutAdjustment(fScrWidthPixel);
	}

	@Override
	public void onClick(View iViewObj)
	{
		int objID;

		objID = iViewObj.getId();
		switch (objID)
		{
			case R.id.view_acctheader_Home:
				SwitchFreeActivity(Trade_tradingOptionActivity.class);
				break;

			case R.id.view_acctheader_Refresh:	
				iViewObj.setClickable(false);
				StockOrderDataRequest();	
				iViewObj.setClickable(true);					
				break;
		}
	}

	// List Click
	@Override
	public void onItemClick(AdapterView<?> iAdapter, View iView, int iIndex,
			long iArgs)
	{
		int objId;

		objId = iAdapter.getId();
		switch (objId)
		{
			case R.id.account_stockorder_List:
			{
				/* Now passing the filter data to data stream */
				Intent intent;
				Bundle bundlePackage;

				bundlePackage = new Bundle();
				intent = new Intent(this,
						Trade_AcctOrderDetailActivity.class);

				bundlePackage.putInt(
						Trade_AppConstant.stockOrderFilterListIndex,
						iIndex);
				bundlePackage.putParcelableArrayList(
						Trade_AppConstant.stockOrderFilterList,
						stockDisplayList);
				intent.putExtras(bundlePackage);

				SwitchForwardActivity(Trade_AcctOrderDetailActivity.class, intent);
			}
				break;
		}
	}

	private static final int	REFRESH_CONTENT	= 1;

	@Override
	public boolean onCreateOptionsMenu(Menu iMenu)
	{
		super.onCreateOptionsMenu(iMenu);
		// Add the menu Item to the menu
		MenuItem menuItemObj = iMenu.add(0, REFRESH_CONTENT, Menu.NONE,
				R.string.updateText);
		menuItemObj.setIcon(R.drawable.ic_menu_lrefresh);
		menuItemObj.setShortcut('0', 'r');

		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem iMenu)
	{
		super.onOptionsItemSelected(iMenu);
		switch (iMenu.getItemId())
		{
			case REFRESH_CONTENT:
				StockOrderDataRequest();
				return true;
		}
		return false;
	}
	
	@Override
	public void onPause()
	{
		if (toastDisplay != null)
			toastDisplay.cancel();

		DetachedDisconnectMessage();	
		
		super.onPause();
	}

	// Use for data viewing
	private ArrayList<Trade_StockHistItem>	stockDisplayList;
	private ListView					stockDisplayListView;
	// Create the array adapter to bind the array to the list view
	private TransactionItemAdapter		stockDisplayListAdapter;
	private static  Toast                   toastDisplay = null;
	
	private void InformationRefresh(STOCK_ORDER_FILTER_TYPE filterType,
			boolean iPrompt)
	{
		int index, count;
		Trade_StockHistItem transItem;
		String processStatus;

		stockDisplayList.clear();

		count = 0;
		if ((transStorageList != null) && !transStorageList.isEmpty())
		{
			count = transStorageList.size();
			if (filterType == STOCK_ORDER_FILTER_TYPE.ALL)
				stockDisplayList.addAll(transStorageList);
			else if (filterType == STOCK_ORDER_FILTER_TYPE.FINISH)
			{
				for (index = 0; index < count; index++)
				{
					transItem = transStorageList.get(index);
					processStatus = transItem.statusCode;
					if ((processStatus
							.equals(Trade_SymbolTranslation.TRANSSTATUS_DONE))
							|| (processStatus
									.equals(Trade_SymbolTranslation.TRANSSTATUS_CANCELED))
							|| (processStatus
									.equals(Trade_SymbolTranslation.TRANSSTATUS_REJECTED)))
						stockDisplayList.add(transItem);
				}
			}
			else if (filterType == STOCK_ORDER_FILTER_TYPE.PROCESSING)
			{
				for (index = 0; index < count; index++)
				{
					transItem = transStorageList.get(index);
					processStatus = transItem.statusCode;
					if ((processStatus
							.equals(Trade_SymbolTranslation.TRANSSTATUS_DONE))
							|| (processStatus
									.equals(Trade_SymbolTranslation.TRANSSTATUS_CANCELED))
							|| (processStatus
									.equals(Trade_SymbolTranslation.TRANSSTATUS_REJECTED)))
						continue;
					stockDisplayList.add(transItem);
				}
			}
		}

		stockDisplayListAdapter.notifyDataSetChanged();
		stockDisplayListView.setSelectionAfterHeaderView();

		if (iPrompt)
		{
			String tmpString;

			if (count == 0)
				tmpString = getString(R.string.youHaveNoRecordText);
			else if (count == 1)
				tmpString = getString(R.string.oneRecordText);
			else
				tmpString = String.valueOf(stockDisplayList.size()) + " "
						+ getString(R.string.NoOfRecordTexts);

			if (toastDisplay != null)
			{
				toastDisplay.cancel();
				toastDisplay.setText(tmpString);
			}
			else
				toastDisplay = Toast.makeText(this, tmpString, Toast.LENGTH_SHORT);
			toastDisplay.show();
		}
	}

	@Override
	public void onCheckedChanged(RadioGroup group, int checkedId)
	{
		int objId;

		objId = group.getId();
		switch (objId)
		{
			case R.id.account_stockorder_OptRadioGroup:
				checkedId = group.getCheckedRadioButtonId();
				if (checkedId == R.id.account_stockorder_OptInProgressRadio)
					filterType = STOCK_ORDER_FILTER_TYPE.PROCESSING;
				else if (checkedId == R.id.account_stockorder_OptDoneRadio)
					filterType = STOCK_ORDER_FILTER_TYPE.FINISH;
				else
					filterType = STOCK_ORDER_FILTER_TYPE.ALL;
				InformationRefresh(filterType, true);
				break;
		}
	}

	// Internal Object
	private class TransactionItemAdapter extends
			ArrayAdapter<Trade_StockHistItem>
	{
		// Reference to the Item List
		private int	itemLayout;

		private int	itemOneWidth, itemTwoWidth, itemThreeWidth;
		private int	redColor, whiteColor, dimYellowColor;
		private int    blueColor;
		private int    greenColor;

		public TransactionItemAdapter(Context iContext, int iListLayout,
				int iItemLayout, int iScrWidth,
				ArrayList<Trade_StockHistItem> iItemList)
		{
			super(iContext, iListLayout, iItemList);
			itemLayout = iItemLayout;
			SetScreenWidth(iScrWidth);

			Resources contRes;
			contRes = getResources();

			redColor = contRes.getColor(R.color.Red);
			whiteColor = contRes.getColor(R.color.White);
			blueColor  = contRes.getColor(R.color.Blue);
			dimYellowColor = contRes.getColor(R.color.DimYellow);
			greenColor = contRes.getColor(R.color.Green);
		}

		public void SetScreenWidth(int iScrWidth)
		{
			float factor = (float) iScrWidth
					/ Trade_AppConstant.designschemeWidth;

			itemOneWidth = (int) (60 * factor);
			itemTwoWidth = (int) (100 * factor);
			itemThreeWidth = (int) (64 * factor);
		}

		private int[]	_listLayout	= new int[] {
										R.drawable.at_acctcombo_lslct_even,
										R.drawable.at_acctcombo_lslct_odd };

		@Override
		public View getView(int iPosition, View iContextView,
				ViewGroup iParent)
		{
			TextView textViewObj, textViewObj2;
			String tmpString, convertString;

			View viewObj;

			viewObj = iContextView;
			if (viewObj == null)
			{
				LayoutInflater inflatObj = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				viewObj = inflatObj.inflate(itemLayout, null);
			}

			Trade_StockHistItem item;
			String processStatus;

			item = getItem(iPosition);
			viewObj.setBackgroundResource(_listLayout[iPosition % 2]);

			if (item != null)
			{
				textViewObj = (TextView) viewObj
						.findViewById(R.id.view_stockorderitemlist_StockCode);
				textViewObj.setWidth(itemOneWidth);
				// textViewObj.setTextColor(contRes.getColor(R.color.White));
				textViewObj.setText(item.stockCode);

				textViewObj = (TextView) viewObj
						.findViewById(R.id.view_stockorderitemlist_StockName);
				textViewObj.setWidth(itemTwoWidth);

				if (systemLang.equals("lang_cht"))
					textViewObj.setText(item.chnName);
				else
					textViewObj.setText(item.engName);

				textViewObj = (TextView) viewObj
						.findViewById(R.id.view_stockorderitemlist_QuantityTitle);
				textViewObj.setWidth(itemThreeWidth);

				textViewObj = (TextView) viewObj
						.findViewById(R.id.view_stockorderitemlist_Quantity);
				convertString = Trade_StockFunctionTools
						.ConvertFormatUnitFromString(
								item.quantity,
								Trade_AppConstant.maxStockQuantityDisplayEntry);
				textViewObj.setText(convertString);

				textViewObj = (TextView) viewObj.findViewById(R.id.view_stockorderitemlist_ConfirmVolume);
				convertString = Trade_StockFunctionTools.ConvertFormatUnitFromString(item.fillQuantity,
											Trade_AppConstant.maxStockQuantityDisplayEntry);
				textViewObj.setText(convertString);
				if (item.fillQuantity.equals("0") == false)
					textViewObj.setTextColor(greenColor);
				else
					textViewObj.setTextColor(whiteColor);

				textViewObj = (TextView) viewObj
						.findViewById(R.id.view_stockorderitemlist_TransType);
				
				//New
				if (item.orderSide.equals(Trade_SymbolTranslation.TRANSACTIONTYPE_BID))
					//textViewObj.setTextColor(greenBlueColor);
					textViewObj.setBackgroundColor(blueColor);
				else if (item.orderSide.equals(Trade_SymbolTranslation.TRANSACTIONTYPE_ASK))
					//textViewObj.setTextColor(redColor);
					textViewObj.setBackgroundColor(redColor);				

				tmpString = Trade_SymbolTranslation
						.TranslateTransTypeAbrev(super.getContext(),
								item.orderSide);
				textViewObj.setText(tmpString);

				
				textViewObj = (TextView) viewObj.findViewById(R.id.view_stockorderitemlist_TransPrice);				
				convertString = Trade_StockFunctionTools.AutoFillInDecimal(item.price, Trade_AppConstant.priceValueStringWithDec);
				
				//Convert to thousand format								
				if (item.currencyCode.equals(TradeAppInfo.CNYCode))
				{
					convertString = TradeAppInfo.CNYSign + Trade_StockFunctionTools.AddFormatToThousand(convertString);
					textViewObj.setTextColor(dimYellowColor);
				}					
				else if (item.currencyCode.equals(TradeAppInfo.USDCode))
				{					
					convertString = TradeAppInfo.USDSign + Trade_StockFunctionTools.AddFormatToThousand(convertString);
					textViewObj.setTextColor(dimYellowColor);					
				}					
				else
				{
					convertString = TradeAppInfo.HKDSign + Trade_StockFunctionTools.AddFormatToThousand(convertString);
					textViewObj.setTextColor(whiteColor);					
				}					
				
				textViewObj.setText(convertString);
				
				
				if (item.orderSide.equals(Trade_SymbolTranslation.TRANSACTIONTYPE_BID))
					textViewObj.setBackgroundColor(blueColor);
				else if (item.orderSide.equals(Trade_SymbolTranslation.TRANSACTIONTYPE_ASK))
					textViewObj.setBackgroundColor(redColor);				
				

				textViewObj = (TextView) viewObj.findViewById(R.id.view_stockorderitemlist_Status1);
				textViewObj2 = (TextView) viewObj.findViewById(R.id.view_stockorderitemlist_Status2);

				// Need to flush the content first
				textViewObj.setText("");
				textViewObj2.setText("");

				processStatus = item.statusCode;
				tmpString = item.statusName;
				// Being Cancel, being rejected
				if (processStatus.equals(Trade_SymbolTranslation.TRANSSTATUS_CANCELED)
						|| processStatus.equals(Trade_SymbolTranslation.TRANSSTATUS_REJECTED))
				{
					textViewObj2.setText(tmpString);
					textViewObj2.setTextColor(redColor);
				}
				else if (processStatus.equals(Trade_SymbolTranslation.TRANSSTATUS_DONE))
				{
					textViewObj2.setText(tmpString);
					textViewObj2.setTextColor(greenColor);
				}
				else
				{
					textViewObj.setText(tmpString);
					textViewObj.setTextColor(whiteColor);

					convertString = Trade_StockFunctionTools.ConvertFormatUnitFromString(
									item.outstandQuantity,
									Trade_AppConstant.maxStockQuantityDisplayEntry);
					textViewObj2.setText(convertString);
					textViewObj2.setTextColor(whiteColor);
				}
			}
			return viewObj;
		}
	}

	private AppDialogOK promptMessage = null;
	private void ShowPromptMessage(String iContent)
	{
		if (promptMessage != null)
			promptMessage.dismiss();
		
		DismissWaitingDialog();
		promptMessage = ShowInfoBox(iContent);
	}
	
	private boolean StockOrderDataRequest()
	{
		if (debugMode)
			TDStockLog.i(GetIdentity(), "*** StockOrderDataRequest");
		
		if (TradeAppInfo.IsDemoAccount() == false)
		{
			if (IsNetworkAvailable() == false)
			{
				ShowPromptMessage(getString(R.string.commErrorText));
				SubscribeAccountOrder();
				return false;
			}
	
			if (TradeAppInfo.HasSessionTimeExpired() == true)
			{
				ShowTimeExpiredBox();
				return false;
			}
		}
		
		if (promptMessage != null)
			promptMessage.dismiss();
		ShowWaitingDialog();

		final TradeGetMultipleOrder orderRequest = new TradeGetMultipleOrder( actContext, TradeAppInfo.GetUserName());
		orderRequest.SendRequest(TradeAppInfo.IsDemoAccount(),
				new ITradeGetMultipleOrderResponse()
				{
					@Override
					public void ResponseFunc(boolean iSuccessfulSend,
							TradeGetMultipleOrderResult iResponse)
					{
						if (iSuccessfulSend == false)
							ShowPromptMessage(getString(R.string.commErrorText));
						else
						{
							HandleGetStockOrderResult(iResponse);
							TradeAppInfo.ClearStockPortfolioRecord();
						}
						SubscribeAccountOrder();
						orderRequest.Dispose();
					}
				});
		return true;
	}

	void HandleGetStockOrderResult(TradeGetMultipleOrderResult iResult)
	{
		AppDialogOK promptDialog;

		promptDialog = null;
		if ((iResult.BrokerMessage != null)
				&& (iResult.BrokerMessage.length() != 0))
		{
			promptDialog = new AppDialogOK(this);
			promptDialog.SetTextContent(iResult.BrokerMessage);
			promptDialog.SetButtonText(R.string.okText);
			// return features are based on specification
		}

		// Login Session expired and kick user out to the login page
		if (iResult.StatusCode.equals("12"))
		{
			DismissWaitingDialog();
			// Back to the previous window, the trading option
			if (promptDialog != null)
			{
				promptDialog.show(new AppDialogOK.IAppDialogOK()
				{
					@Override
					public void OnDialogCancel(DialogInterface iDialog)
					{
						SetToLoginActivity();
					}

					@Override
					public void OnOK_Click(DialogInterface iDialog)
					{
						SetToLoginActivity();
					}

				}, true);
			     return;
			}
			
			SetToLoginActivity();
			return;
		}

		if (iResult.StatusCode.equals("0"))
		{
			TradeAppInfo.SetStockHistoryRecord(iResult.historyItems);
			transStorageList = iResult.historyItems
					.GetStockHistoryRecordList();
			InformationRefresh(filterType, true);
			DismissWaitingDialog();
			return;
		}

		DismissWaitingDialog();
		// Prompt Error if there are one and do not know what to do
		if ((iResult.BrokerMessage != null)
				&& (iResult.BrokerMessage.length() != 0))
		{
			if (promptDialog != null)
				promptDialog.show(null, true);
		}
	}
	
	/* Subscribing for Account on hold invoking by the server */
	private String lsAccountOrderRequest = null;
	private final String AccountChangeSchema = "CMD";
	
	private void SubscribeAccountOrder()
	{
		if (debugMode)
			TDStockLog.i(GetIdentity(), "*** SubscribeAccountOrder");
		
		if (TradeAppInfo.IsDemoAccount())
			return;
		
		//Now we are using light streamer		
		LS_SubscriptionItem acctChangeListen;
		String  deviceID;
			
		if (lsAccountOrderRequest == null)
			lsAccountOrderRequest = LSGetUniqueID();
		
		deviceID = TradeAppInfo.GetDeviceID(actContext);
		
		acctChangeListen = new LS_SubscriptionItem("TRADING");
		acctChangeListen.AddSubscribeItem(deviceID);
		acctChangeListen.AddSubscribeSchema(AccountChangeSchema);
		
		if (LightStreamerSubscribeItem(lsAccountOrderRequest, acctChangeListen, LS_ItemRequestType.NONE, this) == false)
		{		
			ShowPromptMessage(getString(R.string.SubscribeError_Text));
			return;
		}		
	}
	
	private Handler UIHandler = new Handler();
	@Override
	public void onUpdate(String iIdentifier, int iSchemaIndex,
			String iSchemaValue, UpdateInfo iUpdateInfo)
	{		
		String   tmpValue, tmpValue2;
		String[] stringArray;
		
		tmpValue = iUpdateInfo.getNewValue(AccountChangeSchema);
		//Fault
		if ((tmpValue == null) || (tmpValue.length() == 0))
				return;

		if (debugMode)
			TDStockLog.i(GetIdentity(), "AccountUpdate: " + tmpValue);
		stringArray = tmpValue.split(" ");
		
		int      index, count;
		
		count = stringArray.length;
		//Sample o:1234 p:2121
		//We are at the account book, so we will look at the data again		
		for (index = 0; index < count; index++)
		{
			tmpValue  = stringArray[index].trim();
			/* Get the data after the : */
			if (tmpValue.startsWith("o:"))
			{
				tmpValue2 = tmpValue.substring(2);
				if (tmpValue2.equals("0") == false)
				{
					TradeAppInfo.ClearStockHistoryRecord();
					if (debugMode)
						TDStockLog.i(GetIdentity(), "Order book will be needed to updated.");
				}
			}
			else if (tmpValue.startsWith("p:"))
			{
				tmpValue2 = tmpValue.substring(2);	
				if (tmpValue2.equals("0") == false)
				{
					TradeAppInfo.ClearStockPortfolioRecord();					
					if (debugMode)
						TDStockLog.i(GetIdentity(), "Portfolio will be needed to updated.");
				}				
			}
		}
			
		if (TradeAppInfo.IsStockHistoryEmpty())
		{
			Runnable runObject = new Runnable()
			{
				public void run()
				{
					StockOrderDataRequest();
				}
			};
			UIHandler.post(runObject);
		}
	}

	@Override
	public void LS_UserClient_ConnectionReport(CONNECTION_STATUS iStatus)
	{
		if (TradeAppInfo.IsDemoAccount())
			return;

		//Return to the sign in message display for the application
		if (iStatus == CONNECTION_STATUS.CLOSE_BY_FORCE)
		{
			SetToAppLoginActivity();
			return;	
		}
		
		boolean isConnected;
		
		if (iStatus == CONNECTION_STATUS.CONNECTED)
			isConnected = true;
		else
			isConnected = false;
		
		//Set a dummy ui to the display
		if (isConnected)
			DetachedDisconnectMessage();
		else
		{
			DismissWaitingDialog();			
			AttachDisconnectMessage();
		}		
	}

	private PopupWindow lsStatusPopupView = null;
	private View        viewObj = null;
	
	private Runnable popupWindow_runnable = null;	
	private void AttachDisconnectMessage()
	{
		if (lsStatusPopupView == null)
		{
			LayoutInflater inflatObj = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			
			viewObj  = inflatObj.inflate(R.layout.trade_prompt_msgbox, null);
			viewObj.findViewById(R.id.prompt_msgboxContent).setOnClickListener( new OnClickListener()
			{
				@Override
				public void onClick(View arg0)
				{
					boolean status;
					
					status = appHost.LSClient_Connect(new ILS_UserClient_Authentication_Report()
					{
						@Override
						public void LS_UserClient_Authentication_Response(
								LS_UserClient_Authentication_Result iResponse)
						{
							if ((iResponse.successfulSend == false) || (iResponse.statusCode == null) 
								|| !iResponse.statusCode.equals("0"))
							{
								UIHandler.postDelayed(popupWindow_runnable, Trade_AppConstant.timeDelayForPopup);
								return;
							}												
						}											
					});											
					if (status == true)
						DetachedDisconnectMessage();
				}
	
			});					
			lsStatusPopupView = new PopupWindow(viewObj, 
									 LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
			lsStatusPopupView.setAnimationStyle(R.anim.zoom_enter);
			lsStatusPopupView.setOutsideTouchable(true);			
		}
		
		if (!lsStatusPopupView.isShowing())
		{
			if (popupWindow_runnable == null)
			{
				popupWindow_runnable = new Runnable()
				{
					public void run()
					{
						lsStatusPopupView.showAtLocation(viewObj, Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL,
												    0, Trade_AppConstant.popupHeightAboveLoc);
					};
				};
			}
			UIHandler.postDelayed(popupWindow_runnable, Trade_AppConstant.timeDelayForPopup);				
		}			
	}	
	
	private void DetachedDisconnectMessage()
	{
		if (lsStatusPopupView == null)
			return;
		
		if (popupWindow_runnable != null)
			UIHandler.removeCallbacks(popupWindow_runnable);
		
		if (lsStatusPopupView.isShowing())
			lsStatusPopupView.dismiss();
	}	

	@Override
	public void ReporterTicker_Response(int iRemainSecond)
	{	}
}
